﻿using EnvCheck.Services;
using EnvCheck.Utils;
using EnvCheck.View;
using EnvCheck.View.Progress;
using Serilog;
using Serilog.Enrichers.WithCaller;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls.Primitives;

namespace EnvCheck;

public partial class MainWindow : Window
{
    private static readonly MainViewModel ViewModel = new();

    public MainWindow()
    {
        InitializeComponent();
        DataContext = ViewModel;
        InitLoggingModule();

        MainTabControl.Visibility = Visibility.Hidden;
        LoadingIndicatorControl.Visibility = Visibility.Visible;

        Loaded += MainWindow_Loaded; // 注册 Loaded 事件

        var names = Assembly.GetExecutingAssembly().GetManifestResourceNames();
        foreach (var name in names)
        {
            Serilog.Log.Information($"Resource: {name}");
        }
    }

    private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        await Task.Run(() =>
        {
            // 后台线程执行可能耗时的任务
            LoadRegistry();

            ViewModel.RegisterTabs(out int selected);

            // 切换 UI：一定要 Dispatcher.Invoke
            Application.Current.Dispatcher.Invoke(() =>
            {
                MainTabControl.SelectedIndex = selected + 1;
                LoadingIndicatorControl.Visibility = Visibility.Hidden;
                MainTabControl.Visibility = Visibility.Visible;
            });
        });
    }


    private void LoadRegistry()
    {
        Application.Current.Dispatcher.Invoke(() =>
        {
            MainTabControl.Visibility = Visibility.Hidden;
            LoadingIndicatorControl.Visibility = Visibility.Visible;
        });

        // 初始化注册表加载器
        RegistryLoader loader = new()
        {
            Window = this
        };
        InstalledAppService.AsyncLoadInstalledApps(loader, loader);

        Application.Current.Dispatcher.Invoke(() =>
        {
            LoadingIndicatorControl.Visibility = Visibility.Hidden;
            MainTabControl.Visibility = Visibility.Visible;
        });
    }

    private static void InitLoggingModule()
    {
        string logDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
        Directory.CreateDirectory(logDir); // 确保目录存在
        //var outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message} (at {Caller}){NewLine}{Exception}"; ;
        Log.Logger = new Serilog.LoggerConfiguration()
            .MinimumLevel.Debug()
            .Enrich.FromLogContext() // 会添加 CallerMemberName、FilePath、LineNumber 等信息
            .WriteTo.File(
                Path.Combine(logDir, "envcheck.log"),

                //outputTemplate: outputTemplate,
                rollingInterval: RollingInterval.Minute,
                retainedFileCountLimit: 7 // 可选：最多保留最近7天日志
            )
            .CreateLogger();
    }

    private class RegistryLoader : EnvCheck.Utils.IAsyncInstalledAppReceiver, EnvCheck.Utils.IProgressReceiver
    {
        public RegistryLoader() { 

        }
        public MainWindow Window;
        public void ReportProgress(int current, int total)
        {
            LoadingIndicator.ViewModel.ReportProgress(current, total);
        }
        public void Receive(string name, string version)
        {

        }

    }
}
